#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>

#include "gs.h"
#include "hctable.h"

int gs_hctable_init(void)
{
    mkdir("table", 00777);

    return 0;
}

int gs_hctable_data(const char *filename, double height, double* volume)
{
    //TODO
    int h1 = 0.0, h2 = 0.0;
    double v1 = 0.0, v2 = 0.0;
    FILE* fp;

    
    if (height < 0)
    {
        fprintf (stderr, "height < 0\n");
        return -1;
    }

    if (filename == NULL || filename[0] == '\0') {
        return -1;
    }

    fp = fopen (filename, "r");

    if (fp == NULL) {
        printf ("Cannot open %s\n", filename);
        return  -1;
    }
    
    while (!feof(fp))
    {
        fscanf (fp, "%d %lf", &h1, &v1);

        if (h1 < height)
        {
            h2 = h1;
            v2 = v1;
        }
        else
        {
            if (h1 == height)
            {
                *volume = v1;
            }
            else
            {
                *volume = (v2-v1) / (h2-h1) * (height-h1) + v1;
            }

            return 0;
        }
    }
    
    fprintf (stderr, "overflow height range\n");
    return -1;
}

int gs_hctable_fp(int table_id, FILE** fp)
{
#if 0
    int i;

    for (i=0; i<g_gs.nr_tables; i++)
    {
        if (table_id == g_gs.tables[i].table_id)
        {
            *fp = g_gs.tables[i].fp;
            if (*fp == NULL) {
                // fprintf(stderr, "table id = %d: fp is NULL\n", table_id);
                return -1;
            }
            else
                return 0;
        }
    }

    fprintf(stderr, "table id is not exit\n");
#endif
    return -1;
}
